<template>
	<view class="select_address">
		<scroll-view :scroll-top="scrollTop" scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered"
			@refresherrefresh="onRefresh" :refresher-threshold="50" @scrolltolower="scrolltolower"
			class="select_address_view" v-if="dataSouse.length">
			<view class="select_address_body">
				<view class="select_address_card" @click.stop="handleSelect(item)" v-for="item in dataSouse"
					:key="item?.id">
					<view class="select_address_card_left">
						<image src="http://qianxueapplet.suoeryun.com/addressselection.png"
							class="select_address_card_left_select" v-if="item?.id === selectData?.id"></image>
						<image
							src="http://qianxueapplet.suoeryun.com/addressnotselected.png"
							class="select_address_card_left_select" v-else></image>
						<view class="select_address_card_left_info">
							<view class="select_address_card_left_info_1">
								<text>{{item?.consignee}}</text>
								<text>{{maskPhoneNumber(item?.phoneNumber)}}</text>
							</view>
							<view class="select_address_card_left_info_2">
								<template
									v-if="item?.location">{{item?.location?.replaceAll(',','')}}</template>{{item?.address}}
							</view>
						</view>
					</view>
					<image class="select_address_card_right" @click.stop="handleEdit(item)"
						src="http://qianxueapplet.suoeryun.com/bianji.png"></image>
				</view>
				<u-loadmore :status="status" @loadmore="scrolltolower" v-if="status !== 'nomore'"></u-loadmore>
			</view>
		</scroll-view>
		<u-empty v-else marginTop="100" text="您还没有收货地址哟～"
			icon="http://qianxueapplet.suoeryun.com/zwshdz.png"></u-empty>
		<view class="select_address_btm btm_btm">
			<view class="btm_btm_row">
				<button @click="handleEdit(null)" class="row_btn">添加新地址</button>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, reactive, unref, onMounted, toRaw } from 'vue';
	import { qxWxUserDeliveryAddressList, queryFreightByGoodsIdALocationCode } from '@/config/goodStuff.api';
	import { maskPhoneNumber } from '@/util/index';
	import { onLoad } from '@dcloudio/uni-app';


	const dataSouse = ref([]);
	const triggered = ref(false);
	const scrollTop = ref(0);
	const status = ref('loadmore');
	const pagination = reactive({ pageNo: 1, total: 0, pageSize: 10 });

	const selectData = ref();
	const params = ref();

	onLoad((option) => {
		console.log(option, 'selectAddress');
		params.value = option;
	})

	onMounted(async () => {
		loadData();
		selectData.value = null;
		// 默认收货地址
		// const res = await getWxUserDefaultAddress({});
		// selectData.value = res;
		uni.$on('updataAddressList', () => {
			pagination.pageNo = 1;
			uni.showLoading();
			loadData();
		})
	})

	/**
	 * 选择地址
	 */
	async function handleSelect(item) {
		// 待发货
		if (params.value?.orderStatus === '2') {
			uni.showModal({
				content: '是否选择该地址为收货地址？地址只可修改一次，请谨慎操作！',
				confirmColor: '#FF943C',
				success: async (res) => {
					if (res?.confirm) {
						uni.showLoading()
						const res = await queryFreightByGoodsIdALocationCode({ freightTemplateId: unref(params)?.freightTemplateId, locationCode: item?.locationCode?.split(',')[0] });
						handleSelectCallBack({ ...item, freightCharges: res?.freightCharges, templateId: res?.id, templateName: res?.templateName });
					} else { }
				},
				fail: (res) => {
				}
			})
			return
		} else {//待付款
			uni.showLoading()
			const res = await queryFreightByGoodsIdALocationCode({ freightTemplateId: unref(params)?.freightTemplateId, locationCode: item?.locationCode?.split(',')[0] });
			handleSelectCallBack({ ...item, freightCharges: res?.freightCharges, templateId: res?.id, templateName: res?.templateName });
		}
	}

	// 选择回调
	function handleSelectCallBack(item) {
		selectData.value = item;
		uni.navigateBack({
			success() {
				setTimeout(_ => {
					uni.$emit('selectAddress', { orderId: params.value?.orderId, ...item });
				}, 500)
			}
		})
	}

	/**
	 * 编辑地址
	 */
	function handleEdit(item) {
		const record = toRaw(item);
		uni.$u.route('/pages/goodStuff/editAddress', {
			id: record ? record?.id : ''
		});
	}


	/**
	 * 加载数据
	 */
	async function loadData() {
		if (pagination.pageNo === 1) {
			dataSouse.value = [];
		}
		status.value = 'loading';
		const res = await qxWxUserDeliveryAddressList({ ...pagination });
		triggered.value = false;
		pagination.total = res?.total;
		dataSouse.value?.push(...res?.records);
		if (unref(dataSouse)?.length < pagination.total) {
			status.value = 'loadmore';
		} else {
			status.value = 'nomore';
		}
	}


	/**
	 * 滚动到底部操作
	 */
	function scrolltolower() {
		if (unref(dataSouse)?.length < pagination.total && (unref(dataSouse)?.length / pagination.pageSize == pagination.pageNo)) {
			pagination.pageNo++;
			loadData();
		}
	}

	/**
	 * 自定义下拉刷新被触发
	 */
	function onRefresh() {
		triggered.value = true;
		pagination.pageNo = 1;
		loadData();
	}
</script>

<style lang="scss" scoped>
	.select_address {
		padding: 24rpx;

		.select_address_view {
			height: calc(100vh - 74rpx);
		}

		.select_address_body {
			padding-bottom: 74rpx;

			.select_address_card {
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				background-color: #fff;
				padding: 24rpx;
				border-radius: 12rpx;
				margin-bottom: 24rpx;

				.select_address_card_left_info_2 {
					font-size: 28rpx;
					color: #6A6767;
					line-height: 40rpx;
				}

				.select_address_card_left {
					flex: 1;
					display: flex;
					align-items: flex-start;

					.select_address_card_left_select {
						width: 40rpx;
						height: 40rpx;
						margin-right: 20rpx;
						margin-top: 2rpx;
					}

					.select_address_card_left_info {
						flex: 1;

						.select_address_card_left_info_1 {
							font-size: 36rpx;
							font-weight: 500;
							margin-bottom: 10rpx;

							text {
								margin-right: 10rpx;
							}
						}
					}
				}

				.select_address_card_right {
					width: 38rpx;
					height: 38rpx;
					margin-left: 24rpx;
				}
			}
		}
	}
</style>